<template>
  <span v-if="show">
    <el-tooltip content="超时预警" placement="top">
      <i style="font-size:12px;color:#FC6B5C" class="V7_iconfont V7_iconV7tubiao_chaoshi"></i>
    </el-tooltip>
  </span>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { CommonModule } from '@/store/modules/common'
import { WebchatModule } from '@/store/modules/webchat'
/**
 * 超时预警组件
 * @prop visitorStartWaitTimestamp 访客等待时间
 * @prop sessionId 会话id，用于点击浏览器提示跳转
 */
@Component({
  name: 'OverTimeInfo'
})
export default class OverTimeInfo extends Vue {
  [x: string]: any
  @Prop() private item: any
  @Prop() private show: any
  private inter: any = null
  private time: number = 0
  // 超时预警配置
  private globalConfig: any = {
    isTimeoutReplyAlert: false,
    timeoutReplyAlertTime: 60
  }

  @Watch('item', { immediate: true, deep: true })
  private Change (val) {
    if (val.lastMessage && val.lastMessage.lastMessageFrom === 'agent') {
      WebchatModule.REMOVE_WEBCHAT_OVERTIMEINFOLIST(this.item._id)
      this.$emit('update:show', false)
    }
    this.time = val.visitorStartWaitTimestamp
  }

  private mounted () {
    if (this.$store.state.common.publicCache.globalConfig && this.$store.state.common.publicCache.globalConfig.length > 0) {
      this.globalConfig = this.$store.state.common.publicCache.globalConfig[0]
    }
    if (!this.globalConfig.isTimeoutReplyAlert) {
      return false
    }
    this.startInterval()
  }

  private removeInterval () {
    clearInterval(this.inter)
    this.inter = null
    this.$emit('update:show', false)
  }

  private startInterval () {
    this.inter = setInterval(() => {
      if (this.time === 0) {
        return
      }
      if (Date.now() - this.time > this.globalConfig.timeoutReplyAlertTime * 1000) {
        // 同一会话只需提醒一次即可
        if (!WebchatModule.webchatOverTimeInfoList.includes(this.item._id)) {
          CommonModule.NOTIFY({
            title: '通知',
            message: '您有会话客户等待时间过长，请及时处理',
            options: {
              dir: 'auto',
              icon: 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=405069346,3880007726&fm=11&gp=0.jpg',
              body: '您有会话客户等待时间过长，请及时处理'
            },
            routePath: `/im_workBench/index/webchat_todo/${this.item._id}`,
            notifyData: {}
          })
          WebchatModule.ADD_WEBCHAT_OVERTIMEINFOLIST(this.item._id)
        }
        this.$emit('update:show', true)
      }
    }, 1000)
  }

  private beforeDestroy () {
    this.removeInterval()
  }
}
</script>
